<template>
  <div class="modelWrapper">
    <div class="server-table">
      <div class="table-title">
        <span class="table-title-text">模型管理</span>
        <div>
          <el-button type="primary" size="small" @click="openDialog"
            >模型训练</el-button
          >
          <el-button type="primary" size="small" @click="deleteSome"
            >批量删除</el-button
          >
        </div>
      </div>
      <el-table
        :data="tableList"
        @selection-change="selectTableList"
        v-loading="tableLoading"
      >
        <el-table-column
          type="selection"
          width="50"
          align="center"
        ></el-table-column>
        <el-table-column
          type="index"
          label="ID"
          width="50"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="modelName"
          label="模型名称"
          align="center"
          show-overflow-tooltip
          min-width="200"
        >
        </el-table-column>
        <el-table-column
          prop="modelDesc"
          label="版本说明"
          align="center"
          width="150"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          prop="modelVersion"
          label="版本号"
          align="center"
          width="100"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          prop="modelP"
          label="精确度"
          align="center"
          width="150"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          prop="modelR"
          label="召回率"
          align="center"
          show-overflow-tooltip
          width="150"
        >
        </el-table-column>
        <el-table-column
          prop="modelF"
          label="F1值"
          align="center"
          width="150"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          prop="modelStatus"
          label="状态"
          align="center"
          width="200"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            {{
              scope.row.modelStatus == "0"
                ? "训练中"
                : scope.row.modelStatus == "1"
                ? "训练结束未发布"
                : "已发布"
            }}
          </template>
        </el-table-column>
        <el-table-column
          prop="updateTime"
          label="更新时间"
          align="center"
          width="150"
        ></el-table-column>
        <el-table-column label="操作" align="center" width="200">
          <template slot-scope="scope">
            <el-link
              v-if="scope.row.modelStatus == '1'"
              :underline="false"
              type="primary"
              class="ontology-edit"
              @click.native.prevent="release(scope.row.id)"
              >发布
            </el-link>
            <el-link
              :underline="false"
              type="primary"
              class="ontology-edit"
              @click.native.prevent="editModel(scope.row.id)"
              >编辑</el-link
            >
            <el-link
              :underline="false"
              type="primary"
              class="ontology-edit"
              @click.native.prevent="deleteModel(scope.row.id)"
              >删除</el-link
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="km-pagination"
        background
        :small="true"
        layout="total, prev, pager, next,sizes, jumper"
        :total="tableTotal"
        :hide-on-single-page="!tableTotal"
        :page-size.sync="tablePage.page_size"
        :pager-count="7"
        :page-sizes="[10, 20, 30]"
        :current-page="tablePage.page_index"
        @size-change="tableSizeChange"
        @current-change="tableCurrentChange"
      >
      </el-pagination>
    </div>

    <el-dialog
      :title="dialogConfig.title"
      :visible.sync="dialogVisible"
      width="54%"
      class="dialogWrapper"
      @close="afterDialogClose"
    >
      <div class="top">
        <div>
          模型名称: <span>{{ modelName }}</span>
        </div>
        <template v-if="dialogConfig.title === '编辑模型'">
          <div>精确度: {{ modelP }}</div>
          <div>召回率: {{ modelR }}</div>
          <div>F1值: {{ modelF1 }}</div>
        </template>
      </div>
      <el-form
        :model="dialogForm"
        ref="dialogForm"
        :inline="true"
        label-width="80px"
        label-position="right"
        class="form"
      >
        <!-- <el-form-item label="模型名称:" prop="name">
          <el-input size="medium" v-model="dialogForm.name"></el-input>
        </el-form-item> -->
        <el-form-item label="版本号:" prop="version">
          <el-input size="medium" v-model="dialogForm.version"></el-input>
        </el-form-item>
        <el-form-item label="版本说明:" prop="describe" class="describeItem">
          <el-input size="medium" v-model="dialogForm.describe"></el-input>
        </el-form-item>
      </el-form>
      <div class="middle" v-if="dialogConfig.title === '训练模型'">
        <span class="title">选择训练数据集</span>
        <el-form
          :model="dataForm"
          ref="dataForm"
          :inline="true"
          label-width="76px"
          label-position="right"
        >
          <el-form-item label="文件名:" prop="fileName">
            <el-input
              size="medium"
              placeholder="请输入文件名"
              v-model="dataForm.fileName"
            ></el-input>
          </el-form-item>
          <el-form-item label="数据来源:" prop="dataSource">
            <el-select
              size="medium"
              v-model="dataForm.dataSource"
              placeholder="请选择"
            >
              <el-option
                v-for="item in dataSourceOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="抽取模型:" prop="extractModel">
            <el-select
              size="medium"
              v-model="dataForm.extractModel"
              placeholder="请选择"
            >
              <el-option
                v-for="item in extractOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button size="medium" type="primary" @click="searchDataList"
              >查 询</el-button
            >
          </el-form-item>
        </el-form>
      </div>

      <div class="middle" v-else>
        <span class="title">训练数据集</span>
      </div>

      <el-table
        :data="dataList"
        @selection-change="selectDataList"
        v-loading="tableLoading"
        element-loading-text="正在发布..."
        class="km-table"
      >
        <el-table-column
          type="index"
          label="序号"
          width="50"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="fileName"
          label="文件名"
          align="center"
          show-overflow-tooltip
          min-width="300"
        >
        </el-table-column>
        <el-table-column
          prop="sourceData"
          label="数据来源"
          align="center"
          width="150"
        ></el-table-column>
        <el-table-column
          prop="extractModel"
          label="抽取模型"
          align="center"
          width="150"
        ></el-table-column>
        <el-table-column
          v-if="dialogConfig.title === '训练模型'"
          type="selection"
          width="50"
          align="center"
        >
        </el-table-column>
      </el-table>
      <el-pagination
        class="km-pagination"
        background
        :small="true"
        layout="total, prev, pager, next,sizes, jumper"
        :total="dataTotal"
        :hide-on-single-page="!dataTotal"
        :page-size.sync="dataPage.page_size"
        :pager-count="7"
        :page-sizes="[10, 20, 30]"
        :current-page="dataPage.page_index"
        @size-change="dataSizeChange"
        @current-change="dataCurrentChange"
      >
      </el-pagination>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          v-if="dialogConfig.title === '训练模型'"
          @click="trainModel"
          :loading="submitDialogFormLoading"
          >训 练</el-button
        >
        <el-button
          type="primary"
          v-else
          @click="saveModel"
          :loading="submitDialogFormLoading"
          >保 存</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "modelManagement_gener",
  data() {
    return {
      tablePage: {
        page_index: 1, // 页码
        page_size: 10, // 每页条数
      },
      tableList: [],
      tableLoading: false,
      tableSelection: [],
      tableTotal: 0,
      dataSourceOptions: [
        {
          label: "全部",
          value: "",
        },
        {
          label: "人工标注",
          // value: "0"
          value: "人工标注",
        },
        {
          label: "模型抽取",
          // value: "1"
          value: "模型抽取",
        },
      ],
      extractOptions: [
        {
          label: "全部",
          value: "",
        },
        {
          label: "文本抽取模型",
          value: "文本抽取模型",
        },
        {
          label: "/",
          value: "/",
        },
      ],
      dialogVisible: false,
      currentModelId: "", // 当前编辑项模型的 id
      modelName: "",
      modelR: "",
      modelP: "",
      modelF1: "",
      dialogForm: {
        version: "",
        describe: "",
      },
      dataPage: {
        page_index: 1, // 页码
        page_size: 10, // 每页条数
      },
      dataList: [],
      dataLoading: false,
      dataSelection: [],
      dataTotal: 0,

      dataForm: {
        fileName: "文本抽取模型",
        dataSource: "",
        extractModel: "",
      },
      submitDialogFormLoading: false,
      dialogConfig: {
        title: "训练模型",
      },
    };
  },
  created() {
    this.getTableList();
  },
  methods: {
    // 获取管理列表数据
    async getTableList() {
      let params = {
        pageNum: this.tablePage.page_index,
        pageSize: this.tablePage.page_size,
      };
      let res = await this.$api.knowledgeGeneration.getAllModel(params);
      const { code, data, message } = res.data;
      if (+code === 200) {
        this.tableList = data.list;
        this.tableTotal = data.total;
      }
    },
    // 打开训练模型弹窗
    openDialog() {
      this.dialogConfig.title = "训练模型";
      this.dialogVisible = true;
      // 获取数据集列表数据
      this.getDataList();
    },
    // 获取数据集列表数据
    async getDataList(arg) {
      let params = {
        fileName: arg ? arg.fileName : "",
        sourceOfData: arg ? arg.sourceOfData : "",
        extractModel: arg ? arg.extractModel : "",
        pageIndex: this.dataPage.page_index,
        pageSize: this.dataPage.page_size,
      };
      let res = await this.$api.knowledgeGeneration.openModelTraning(params);
      const { code, data, message } = res.data;
      if (+code === 200) {
        // console.log("dadtaa", data);
        this.modelName = data.modelName;
        this.dialogForm.version = data.modelVersion;
        this.dialogForm.describe = data.modelDesc;
        this.dataList = data.traningDataList.list;
        this.dataTotal = data.traningDataList.total;
      }
    },
    // 查询方法
    searchDataList() {
      const {
        dataSource: sourceOfData,
        extractModel,
        fileName,
      } = this.dataForm;
      let query = {
        fileName,
        extractModel,
        sourceOfData,
        pageIndex: this.dataPage.page_index,
        pageSize: this.dataPage.page_size,
      };
      this.getDataList(query);
    },

    // 主管理表的选中方法
    selectTableList(val) {
      this.tableSelection = val;
    },
    // 数据集表的选中方法
    selectDataList(val) {
      this.dataSelection = val;
    },
    async publishModel(id) {
      let params = {
        id,
      };
      this.$api.knowledgeGeneration
        .changeModel(params)
        .then((res) => {
          const { code, data, message } = res.data;
          this.tableLoading = false;
          if (+code === 200) {
            this.getTableList();
            this.$message.success(message);
            return false;
          }
          this.$message.error(message);
        })
        .catch((err) => {
          throw new Error("请求失败");
        });
    },
    // 发布
    release(id) {
      this.$confirm(
        "是否确认发布该版本模型？发布后，系统将默认使用已发布状态的模型。",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          this.tableLoading = true;
          this.publishModel(id);
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消发布",
          });
        });
    },
    // 编辑模型
    editModel(id) {
      this.dialogVisible = true;
      this.dialogConfig.title = "编辑模型";
      this.currentModelId = id;
      this.updateModel(id);
    },
    async updateModel(id) {
      let params = {
        modelId: id,
      };
      let res = await this.$api.knowledgeGeneration.updateModel(params);
      const { code, data, message } = res.data;
      if (+code === 200) {
        this.modelName = data.paperModel.modelName;
        this.dialogForm.version = data.paperModel.modelVersion;
        this.dialogForm.describe = data.paperModel.modelDesc;
        this.modelR = data.paperModel.modelR;
        this.modelP = data.paperModel.modelP;
        this.modelF1 = data.paperModel.modelF1;
        this.dataList = data.traningDataList.list;
        this.dataTotal = data.traningDataList.total;
      }
    },

    async deleteFun(arg) {
      let params = {
        ids: arg,
      };
      let res = await this.$api.knowledgeGeneration.deleteModel(params);
      const { code, data, message } = res.data;
      if (+code !== 200) {
        return false;
      }
      return true;
    },

    // 删除模型
    deleteModel(idArr) {
      this.$confirm(
        "是否确认删除所选模型？删除后模型不可恢复，请谨慎操作。",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          const params = Array.isArray(idArr) ? idArr : [idArr];
          let result = this.deleteFun(params);
          if (result) {
            this.$message.success("删除成功!");
            this.getTableList();
          } else {
            this.$message.error("删除失败!");
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    // 批量删除模型
    deleteSome() {
      if (this.tableSelection.length == 0) {
        this.$message.warning("请勾选需要删除的模型");
      }
      let result = [];
      this.tableSelection.forEach((item) => {
        result.push(item.id);
      });
      this.deleteModel(result);
    },

    // 管理列表调整每页显示数量
    tableSizeChange(e) {
      this.tablePage.page_size = e;
      this.getTableList();
    },
    // 管理列表跳转页面
    tableCurrentChange(e) {
      this.tablePage.page_index = e;
      this.getTableList();
    },

    // 数据集列表调整每页显示数量
    dataSizeChange(e) {
      this.dataPage.page_size = e;
      this.getDataList();
    },
    // 数据集列表跳转页面
    dataCurrentChange(e) {
      this.dataPage.page_index = e;
      this.getDataList();
    },
    // 训练模型
    async trainModel() {
      let idsPerson = [];
      let idsModel = [];
      let idsObj = {};
      this.dataSelection.forEach((item) => {
        if (item.sourceData === "人工标注") {
          idsPerson.push(item.recordId);
        } else {
          idsModel.push(item.recordId);
        }
      });
      idsObj["0"] = idsPerson;
      idsObj["1"] = idsModel;

      const {
        version: modelVersion,
        describe: modelExplanation,
      } = this.dialogForm;

      let params = {
        modelVersion,
        modelExplanation,
        modelName: this.modelName,
        ids: idsObj,
      };
      let res = await this.$api.knowledgeGeneration.trainModel(params);
      const { code, data, message } = res.data;
      if (+code == 200) {
        this.$message.success("训练成功!");
        this.dialogVisible = false;
        this.getTableList();
        return;
      }
      this.$message.error(message);
      this.dialogVisible = false;
    },
    // 保存模型
    async saveModel() {
      const { version: modelVersion, describe: modelDesc } = this.dialogForm;
      let params = {
        modelId: this.currentModelId,
        modelVersion,
        modelDesc,
      };
      let res = await this.$api.knowledgeGeneration.saveModel(params);
      const { code, data, message } = res.data;
      if (+code === 200) {
        this.$message.success("更新成功!");
        this.dialogVisible = false;
        this.getTableList();
        return;
      }
      this.$message.error(message);
      this.dialogVisible = false;
    },

    // 模态框关闭后
    afterDialogClose() {
      this.$refs.dialogForm && this.$refs.dialogForm.resetFields();
      this.$refs.dataForm && this.$refs.dataForm.resetFields();
    },
  },
};
</script>

<style lang="scss" scoped>
.modelWrapper {
  .server-table {
    margin-top: 16px;
    padding: 16px 32px 64px;
    background: #ffffff;
    border-radius: 4px;

    .table-title {
      display: flex;
      justify-content: space-between;
      align-items: center;

      &-text {
        margin: 8px 0;
        font-size: 16px;
        line-height: 16px;
        border-left: 5px solid $--color-primary;
        padding-left: 10px;
      }

      margin-bottom: 10px;
    }

    .ontology-edit {
      padding: 0 10px;

      & + .ontology-edit {
        border-left: 1px solid #dddddd;
      }
    }
  }

  .dialog-inline {
    /deep/ .el-form-item__content {
      width: 300px;
    }

    button.el-button {
      background-color: $--color-primary !important;
      color: #fff !important;
      line-height: 1.2;
    }
  }

  .dialogWrapper {
    /deep/ .el-dialog__body {
      padding-top: 16px;
    }

    .top {
      display: flex;
      // justify-content: space-between;
      margin-bottom: 16px;
      margin-left: 10px;

      span {
        margin-left: 10px;
      }
    }

    .top > div:not(:first-child) {
      margin-left: 10%;
    }

    .form {
      .el-form-item {
        width: 100%;
        margin-bottom: 10px;
      }

      .describeItem {
        /deep/ .el-form-item__content {
          width: 90%;
        }
      }
    }

    .middle {
      margin-top: 20px;

      .title {
        font-weight: 600;
      }
    }
  }
}
</style>
